//
//  WXLoginEngine.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/12/11.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import soapp
import Alamofire
public class WXLoginEngine:NSObject,LoginEngine{
    public lazy var ID:String = {return LoginPlatform.wx.rawValue}()

    public var platform: LoginPlatform {
        get{
            return LoginPlatform.wx
        }
    }
    
    public var delegate: PlatformLoginDelegate?
    public static var shared = WXLoginEngine()
    public var valid = false
    
    public var userInfo:BasePlatformUserInfo = BasePlatformUserInfo(openID: "", accessToken: "", nickName:"", userHead: "",sex:SexType.男,info:NSMutableDictionary())
    

    public func getAccessToken(code:String) {
        var params = [String:Any]()
        params["appid"] = SDKConfig.WX.appID
        params["secret"] = SDKConfig.WX.secret
        params["code"] = code
        params["grant_type"] = "authorization_code"
        
        var _userinfo = self.userInfo
        _userinfo.plat = self.platform
        let _plat = self.platform
        weak var wself = self
        JoTask().get.log.log_response().params(params).wxurl(.accessToken).json_handle { (success, msg, obj, resp,tsk) in
            
            guard let data = (resp as? AFDataResponse<Any>)?.data else {
                wself?.postLoginFiailed(msg: "未能获取access_token")
                return
            }
            do {
            
                if let dict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                {
                    
                    let info = dict.mutable_dictionary
                    if info["openid",""].len < 10
                    {
                        wself?.postLoginFiailed(msg: "未能获取access_token")
                        return
                    }
                    
                    _userinfo.accessToken = info["access_token",""]
                    _userinfo.openID = info["openid",""]
                    _userinfo.info["login"] = info
       
                    wself?.userInfo = _userinfo
                    let result = LoginResult.success(_plat, userInfo: _userinfo)
                    let progress = LoginProgress.finishLogin(result)
                    wself?.delegate?.observerLoginProgress(progress: progress)
                    wself?.getUserInfo()
                }
                else{
                    wself?.postLoginFiailed(msg: "未能获取access_token")
                }
                
            } catch {
                wself?.postLoginFiailed(msg:"\(error)")
                print(error)
            }
            
        }.run()
    }
    
    
    open func getUserInfo() {
        
        
        let progress1 = LoginProgress.beginGetUserInfo(platform)
        self.delegate?.observerLoginProgress(progress: progress1)
        
        var params = [String:Any]()
        params["openid"] = userInfo.openID
        params["access_token"] = userInfo.accessToken
        var _userinfo = self.userInfo
        _userinfo.plat = self.platform
        let _plat = self.platform
        weak var wself = self
        JoTask().get.log.log_response().params(params).wxurl(.userinfo).json_handle { (success, msg, obj, resp,tsk) in
            
            guard let data = (resp as? AFDataResponse<Any>)?.data else {
                wself?.postGetUserInfoFiailed(msg: "未能获取微信用户信息")
                return
            }
            do {
                
                if let dict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                {
                    let info = dict.mutable_dictionary
                    let errmsg =  info["errmsg","信息获取失败"] + " " + "微信获取用户信息接口"

                    
                    if info["openid",""].len < 10
                    {
                        wself?.postGetUserInfoFiailed(msg: errmsg)
                        return
                    }
                    _userinfo.nickName = info["nickname",""]
                    _userinfo.userHead = info["headimgurl",""]
                    _userinfo.info["userInfo"] = info
                    wself?.userInfo = _userinfo

                    
                    let result = LoginResult.success(_plat, userInfo: _userinfo)
                    let progress = LoginProgress.finishGetUserInfo(result)
                    wself?.delegate?.observerLoginProgress(progress: progress)
                 
                    
                }
                else{
                    wself?.postGetUserInfoFiailed(msg: "未能获取微信用户信息")
                }
                
            } catch {
                wself?.postGetUserInfoFiailed(msg:"\(error)")
            }
        }.run()
    }
    
    
    
    public func postLoginFiailed(msg:String) {
        let result = LoginResult.err(platform, err: msg)
        let progress = LoginProgress.finishLogin(result)
        self.delegate?.observerLoginProgress(progress: progress)
    }
    
    public func postGetUserInfoFiailed(msg:String) {
        let result = LoginResult.err(platform, err: msg)
        let progress = LoginProgress.finishGetUserInfo(result)
        self.delegate?.observerLoginProgress(progress: progress)
    }
    
    
    public func handleAuth(respones:SendAuthResp) {
        if !valid{
            return
        }
        if respones.code == nil{
            let result = LoginResult.canle(platform)
            let progress = LoginProgress.finishLogin(result)
            self.delegate?.observerLoginProgress(progress: progress)
        }
        else{
            if let code = respones.code{
                getAccessToken(code: code)
            }
        }
    }

  
    
    
    public func login()
    {
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo"
        req.state = "\(SDKConfig.WX.appID)_wx"
        WXApi.send(req)
        let progress = LoginProgress.beginLogin(platform)
        self.delegate?.observerLoginProgress(progress: progress)
    }
    
}
